/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  Platform,
  TouchableOpacity,
  View,
  Image,
  TouchableHighlight,
} from 'react-native';
import Head from './head.js';
import VisitCustDetail from './visitCustDetail.js';
import GiftedListView from 'react-native-gifted-listview';

let _this;
let l = [];
// let p = [];
export default class VisitCustInfo extends Component {
    constructor(props) {
      super(props);
      this.state = {
          card: '',
          name: '',
          results: [],
      };
      _this = this;
    }

//    用户详情页面
    toVisitCustDetail(rowData) {
        console.warn(JSON.stringify(rowData))
        const { navigator, p_navigator } = this.props;
        if (navigator) {
            navigator.push({
                component: VisitCustDetail,
                params:{
                    SendInfo:rowData
                }
            })
        }
    }

    _getInputName(name){
        //第一个输入框的内容
        this.setState({
            name:name
        })
    }
    _getInputCard(card){
        //第二个输入框的内容
        this.setState({
            card:card
        })
    }
   

//    查询按钮
  query() {
    // this.setState({
    //     results: searchItems
    // })
    this.refs.gifted._refresh();
  }

  componentWillMount(){
    for(var i = 0; i<items.length;i++){
        let j = {}
        j.card = items[i].card;
        j.name = items[i].name;
        j.location = items[i].location;
        storage.save({
            key: String(items[i].card),
            rawData: { 
                PersonalInfo: j
            },
            expires: null
        })
    }
  }


// 插件的相干方法调用*****************************************start
      _onFetch(page = 1, callback, options) {
          let  p = [];
            for(var i = 0; i<items.length;i++){
                storage.load({
                    key: String(items[i].card),
                }).then(ret => {
                    p.push(ret.PersonalInfo) ;
                })
            }
            setTimeout(() => {
              var header = '第'+page+'页 '
              let rows = {};
              rows[header] = p;
              if (page === 3) {
                callback(rows, {
                  allLoaded: true, // 到达列表的结尾
                });
              } else {
                callback(rows);
              }
            }, 500) // simulating network fetching
    }
 
  _renderRowView(rowData) {
        return (
          <View  style={{height:50,justifyContent: 'center',padding:10,borderColor:'#CCC',borderBottomWidth:1}}>
            <TouchableOpacity onPress = {this.toVisitCustDetail.bind(this, rowData)}>
                <View style={{justifyContent:'space-between',flexDirection:'row',}}>
                      <View style={{flexDirection:'column'}}>
                            <View style = {{flexDirection:'row',marginBottom:5}}>
                                <Text style = {{fontSize:16,marginRight:150}}>{rowData.name}</Text>
                                <Text style ={{fontSize:16}}>{rowData.card}</Text>
                            </View>
                            <Text style = {{fontSize:16}}>{rowData.location}</Text>
                      </View>
                    <View style={{justifyContent:'center'}}>
                        <Image
                          style={{width: 20, height: 20}}
                          source={require('../images/right_black.png')}
                        />
                    </View>
                </View>
            </TouchableOpacity>
        </View>
        )
  }

  _renderSectionHeaderView(sectionData, sectionID) {
    return (
      <View style={customStyles.header}>
        <Text style={customStyles.headerTitle}>
            {sectionID}
        </Text>
      </View>
    );
  }
  /**
   * Render the refreshable view when waiting for refresh
   * On Android, the view should be touchable to trigger the refreshCallback
   * @param {function} refreshCallback The function to call to refresh the listview
   */
  _renderRefreshableWaitingView(refreshCallback) {
    if (Platform.OS !== 'android') {
      return (
        <View style={customStyles.refreshableView}>
          <Text style={customStyles.actionsLabel}>
            ↓
          </Text>
        </View>
      );
    } else {
      return (
        <TouchableHighlight
          underlayColor='#c8c7cc'
          onPress={refreshCallback}
          style={customStyles.refreshableView}
        >
          <Text style={customStyles.actionsLabel}>
            ↻
          </Text>
        </TouchableHighlight>
      );
    }
  }

  /**
   * 渲染刷新视图的下拉刷新时被激活
   * @platform ios
   */
  _renderRefreshableWillRefreshView() {
    return (
      <View style={customStyles.refreshableView}>
        <Text style={customStyles.actionsLabel}>
          ↻
        </Text>
      </View>
    );
  }

  /**
   * 加载更多
   */
  _renderPaginationWaitingView(paginateCallback) {
    return (
      <TouchableHighlight
        underlayColor='#c8c7cc'
        onPress={paginateCallback}
        style={customStyles.paginationView}
      >
        <Text style={[customStyles.actionsLabel, {fontSize: 13}]}>
            加载更多
        </Text>
      </TouchableHighlight>
    );
  }

  /**
   * 到底部的时候  没有新的数据了
   */
  _renderPaginationAllLoadedView() {
    return (
      <View style={customStyles.paginationView}>
        <Text style={[customStyles.actionsLabel, {fontSize: 13}]}>
              没有更多了
        </Text>
      </View>
    );
  }

  /**
   * 在第一次读取时没有行显示时呈现视图
   * refreshcallback函数调用刷新列表
   */
  _renderEmptyView(refreshCallback) {
    return (
      <View style={customStyles.defaultView}>
        <Text style={customStyles.defaultViewTitle}>
          没有显示的内容
        </Text>

        <TouchableHighlight
          underlayColor='#c8c7cc'
          onPress={refreshCallback}  //调用刷新列表
        >
          <Text>
            ↻
          </Text>
        </TouchableHighlight>
      </View>
    );
  }

  /**
   * Render a separator between rows
   */
  _renderSeparatorView(sectionID,rowID) {
    return (
      <View style={customStyles.separator} key={"sectionID_"+sectionID + "_rowID_"+rowID}/>
    );
  }
  // 插件的相干方法调用*****************************************end
  render() {
    return (
      <View style={styles.container}>
         
          <View style={styles.title}>
              <Head title='调查' />
          </View>

           <View style={{height:110}}>
                <View style={{justifyContent:'space-between',marginTop:10,flex:1,flexDirection:'row',}}>
                      <View style={{flex:1,marginLeft:10}}>
                          <TextInput
                              style={styles.input}
                              underlineColorAndroid='transparent'
                              onChangeText={(text) => this._getInputName(text)}
                              placeholder='请输入名字'
                          />
                          <TextInput
                              style={[styles.input,{marginTop:10}]}
                              underlineColorAndroid='transparent'
                              onChangeText={(text) => this._getInputCard(text)}
                              placeholder='请输入身份证号码'
                          />
                      </View>

                      <View>
                        <TouchableOpacity onPress={ () => {this.query()}}>
                            <View style={styles.queryStyle} >
                                <Text>查询</Text>
                            </View>
                        </TouchableOpacity>
                      </View>
                  </View>
            </View>   
            <View style={{flex:1}}>
                <GiftedListView
                      ref="gifted"
                      rowView={this._renderRowView.bind(this)}
                      onFetch={this._onFetch}
                      initialListSize={12} // the maximum number of rows displayable without scrolling (height of the listview / height of row)
                      firstLoader={true} // display a loader for the first fetching
                      pagination={true} // enable infinite scrolling using touch to load more
                      paginationAllLoadedView={this._renderPaginationAllLoadedView}
                      paginationWaitingView={this._renderPaginationWaitingView}
                      refreshable={true} // enable pull-to-refresh for iOS and touch-to-refresh for Android
                      refreshableViewHeight={50} // correct height is mandatory
                      refreshableDistance={40} // the distance to trigger the pull-to-refresh - better to have it lower than refreshableViewHeight
                      refreshableWillRefreshView={this._renderRefreshableWillRefreshView}
                      refreshableWaitingView={this._renderRefreshableWaitingView}
                      emptyView={this._renderEmptyView}
                      renderSeparator={this._renderSeparatorView}
                      withSections={true} // enable sections
                      sectionHeaderView={this._renderSectionHeaderView}
                      PullToRefreshViewAndroidProps={{colors: ['#fff'],progressBackgroundColor: '#003e82',}}

                      rowHasChanged={(r1,r2)=>{r1.id !== r2.id}}
                      distinctRows={(rows)=>{
                        var indentitis = {};var newRows = [];
                        for(var i = 0;i<rows.length; i++){
                          if(indentitis[rows[i].id]){
                          }else{
                            indentitis[rows[i].id]=true;
                            newRows.push(rows[i]);
                          }
                        }
                        return newRows;
                      }}
                    />
            </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:'#fff'
  },
  title: {
    height:60,
  },
  input: {
    borderColor:'#12b7f5',
    borderWidth:1,
    borderRadius: 5,
    overflow:'hidden',
    height:40,
  },
   queryStyle: {
    width: 50,
    height: 50,
    marginLeft:10,
    marginRight:10,
    borderRadius:5,
    backgroundColor: '#12b7f5',
    marginTop: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  ListViewStyle: {
    height:50,
    borderTopWidth:1,
    borderColor:'#cdcdcd',
    justifyContent: 'center',
    padding:10,
  },
});
const customStyles = StyleSheet.create({
  separator: {
    // height: 1,
    // backgroundColor: '#CCC'
  },
  refreshableView: {
    height: 50,
    backgroundColor: '#fff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  actionsLabel: {
    fontSize: 18,
    color: '#12b7f5',
  },
  paginationView: {
    height: 44,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFF',
  },
  defaultView: {
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  defaultViewTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 15,
  },
  row: {
    padding: 10,
    height: 44,
  },
  header: {
    // backgroundColor: '#50a4ff',
    // padding: 10,
    height:0,
    // borderTopWidth:1,
    // borderColor:'#CCC'
  },
  headerTitle: {
    color: '#fff',
    fontSize:17
  },
})
const defaultStyles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFF',
  },
  navBar: {
    height: 64,
    backgroundColor: '#007aff',

    justifyContent: 'center',
    alignItems: 'center',
  },
  navBarTitle: {
    color: '#fff',
    fontSize: 16,
    marginTop: 12,
  }
})

